//
//  ClassmateViewController.m
//  moon
//
//  Created by beyself on 16/6/18.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import "Utils.h"
#import "ClassmateViewController.h"
#import "UIImageView+AFNetworking.h"
#import "ChatViewController.h"
#import "ClassNickViewController.h"
#import "MateInfoViewController.h"

@interface ClassmateViewController ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation ClassmateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"班级联系人";
    
    _mArray = [[NSMutableArray alloc] init];
    
    UITableView* tableview = [[UITableView alloc] init];
    tableview.backgroundColor = [UIColor clearColor];
    tableview.tag = 10000;
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    tableview.delegate = self;
    tableview.dataSource = self;
    tableview.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:tableview];
    
    UIView* head = [[UIView alloc] init];
    head.backgroundColor = BG;
    head.frame = CGRectMake(0, 0, SCREEN_WIDTH, 3*54 + 10);
    tableview.tableHeaderView = head;
    
    for(int i = 0; i < 3; i++)
    {
        UIButton* button  = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 2100 + i;
        button.frame = CGRectMake(0, 54*i, SCREEN_WIDTH, 54);
        button.titleLabel.font = FONT_13;
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button setTitleColor:BLACK forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:WHITE] forState:UIControlStateDisabled];
        [button setBackgroundImage:[Utils imageFromColor:WHITE] forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if(i < 2)
        {
            button.enabled = NO;
            if(i == 0) [button setTitle:@"班级名称" forState:UIControlStateDisabled];
            else [button setTitle:@"班级成员" forState:UIControlStateDisabled];
            
            UILabel* label = [[UILabel alloc] init];
            label.frame = CGRectMake(90, 0, SCREEN_WIDTH - 100, 54);
            label.textColor = BLUE;
            label.font = FONT_13;
            label.textAlignment = NSTextAlignmentRight;
            label.tag = 100;
            [button addSubview:label];
        }
        else
        {
            [button setTitle:@"备注名称" forState:UIControlStateNormal];
            
            UILabel* label = [[UILabel alloc] init];
            label.frame = CGRectMake(90, 0, SCREEN_WIDTH - 130, 54);
            label.textColor = BLUE;
            label.font = FONT_13;
            label.textAlignment = NSTextAlignmentRight;
            label.tag = 100;
            [button addSubview:label];
            
            UIButton* arrow = [UIButton buttonWithType:UIButtonTypeCustom];
            arrow.frame = CGRectMake(SCREEN_WIDTH - 48, 0, 48, 54);
            [arrow setImage:[UIImage imageNamed:@"ic_arrow"] forState:UIControlStateNormal];
            [button addSubview:arrow];
        }
        
        CALayer* layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 53.5, SCREEN_WIDTH, .5);
        layer.backgroundColor = BG.CGColor;
        [button.layer addSublayer:layer];
        [head addSubview:button];
    }
    
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setValue:_mClassId forKey:@"class_id"];
    [Utils sendHttpPost:param method:@"get_class_member_list" controller:self flag:0];
}

- (void) httpCallback:(NSDictionary*)data flag:(int)flag
{
    [_mArray setArray:data[@"members"]];
    UIView* heaview = ((UITableView*)[self.view viewWithTag:10000]).tableHeaderView;
    ((UILabel*)[[heaview viewWithTag:2101] viewWithTag:100]).text = [NSString stringWithFormat:@"%d人",_mArray.count];
    [(UITableView*)[self.view viewWithTag:10000] reloadData];
}

- (void) buttonClick:(UIButton*)btn
{
    if(btn.tag == 2102)
    {
        ClassNickViewController* subview = [[ClassNickViewController alloc] init];
        subview.mClassId = _mClassId;
        [self.navigationController pushViewController:subview animated:YES];
    }
    else
    {
        int index = [[btn titleForState:UIControlStateDisabled] intValue];
        NSDictionary* item = _mArray[index];
        
        if(btn.tag == 1002)
        {
            [self makeCall:item[@"telephone"]];
        }
        else if(btn.tag == 1003)
        {
            [self sendSms:item[@"telephone"]];
        }
        else
        {
            if([[item[@"id"] description] isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]])
            {
                [self showAllTextDialog:@"不能与自己聊天"];
            }
            else if([item[@"is_active"] intValue] == 0)
            {
                [self showAllTextDialog:@"该用户还未激活"];
            }
            else
            {
                ChatViewController *chat = [[ChatViewController alloc]init];
                chat.conversationType = ConversationType_PRIVATE;
                chat.targetId = [item[@"id"] description];
                [self.navigationController pushViewController:chat animated:YES];
            }
        }
    }
}

- (void) makeCall:(NSString*)tel
{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",tel];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

- (void) sendSms:(NSString*)tel
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"sms://%@",tel]];
    [[UIApplication sharedApplication] openURL:url];
}

- (void) viewWillAppear:(BOOL)animated
{
    NSArray* array = APPDELEGATE.mMemberInfo[@"classes"];
    for(int i = 0; i < array.count; i++)
    {
        NSDictionary* item = array[i];
        if([self.mClassId isEqualToString:[item[@"id"] description]])
        {
            NSString* className = item[@"class_alias"];
            UIView* heaview = ((UITableView*)[self.view viewWithTag:10000]).tableHeaderView;
            ((UILabel*)[[heaview viewWithTag:2100] viewWithTag:100]).text = item[@"class_name"];
            if(![Utils isStringNullOrEmpty:className]) ((UILabel*)[[heaview viewWithTag:2102] viewWithTag:100]).text = className;
            else ((UILabel*)[[heaview viewWithTag:2102] viewWithTag:100]).text = @"";
        }
    }
    
    [(UITableView*)[self.view viewWithTag:10000] reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _mArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
        cell.backgroundColor = WHITE;
        
        UIImageView* imageview = [[UIImageView alloc] init];
        imageview.frame = CGRectMake(10, 7, 40, 40);
        imageview.contentMode = UIViewContentModeScaleAspectFill;
        imageview.layer.cornerRadius = 20;
        imageview.layer.masksToBounds = YES;
        imageview.tag = 1000;
        [cell addSubview:imageview];
        
        UILabel* label = [[UILabel alloc] init];
        label.frame = CGRectMake(60, 0, SCREEN_WIDTH - 160, 54);
        label.tag = 1001;
        label.textColor = BLUE;
        label.font = FONT_13;
        [cell addSubview:label];
        
        label = [[UILabel alloc] init];
        label.font = FONT_10;
        label.frame = CGRectMake(100, 12, 32, 16);
        label.textColor = WHITE;
        label.tag = 3003;
        label.text = @"老师";
        label.hidden = YES;
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = ORANGE;
        label.layer.cornerRadius = 3;
        label.layer.masksToBounds = YES;
        [cell addSubview:label];
        
        for(int i = 2; i < 3; i++)
        {
            UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(SCREEN_WIDTH - (3 - i)*32, 0, 32, 54);
            button.tag = 1002 + i;
            [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            if(i == 0)
            {
                [button setImage:[UIImage imageNamed:@"ic_call"] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"ic_call_focus"] forState:UIControlStateHighlighted];
            }
            if(i == 1)
            {
                [button setImage:[UIImage imageNamed:@"icon_mail"] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"icon_mail_focus"] forState:UIControlStateHighlighted];
            }
            if(i == 2)
            {
                [button setImage:[UIImage imageNamed:@"icon_talk"] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"icon_talk_focus"] forState:UIControlStateHighlighted];
            }
           /*
            if(i > 0)
            {
                CALayer* layer = [[CALayer alloc] init];
                layer.frame = CGRectMake(0, 18, .5, 18);
                layer.backgroundColor = LINE.CGColor;
                [button.layer addSublayer:layer];
            }*/
            
            [cell addSubview:button];
        }
        
        CALayer* layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 0, SCREEN_WIDTH, .5);
        layer.backgroundColor = BG.CGColor;
        [cell.layer addSublayer:layer];
    }
    
    NSDictionary* item = _mArray[indexPath.row];
    
    [(UIButton*)[cell viewWithTag:1002] setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
    [(UIButton*)[cell viewWithTag:1003] setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
    [(UIButton*)[cell viewWithTag:1004] setTitle:[NSString stringWithFormat:@"%d",(int)indexPath.row] forState:UIControlStateDisabled];
    
    UIImageView* imageview = (UIImageView*)[cell viewWithTag:1000];
    if([item[@"is_teacher"] intValue] == 0)
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,item[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_family"]];
    else
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,item[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_teacher"]];
    
    NSMutableString* identity = [NSMutableString stringWithCapacity:64];
    
    if([[item[@"id"] description] isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]]) [identity setString:@"我"];
    else if([item[@"is_teacher"] intValue] == 0)
    {
        NSArray* child = item[@"child"];
        for(NSDictionary* one in child)
        {
            if([[one[@"class_id"] description] isEqualToString:_mClassId])
            {
                if(![Utils isStringNullOrEmpty:one[@"name"]]) [identity appendString:one[@"name"]];
                if(![Utils isStringNullOrEmpty:one[@"identity"]]) [identity appendString:one[@"identity"]];
                break;
            }
        }
        if(![Utils isStringNullOrEmpty:item[@"identity"]]) [identity appendString:item[@"identity"]];
    }
    else if([self getUsername:[item[@"id"] description]] && [self getUsername:[item[@"id"] description]].length)
    {
        [identity setString:[self getUsername:[item[@"id"] description]]];
    }
    else [identity setString:item[@"username"]];
    ((UILabel*)[cell viewWithTag:1001]).text = identity;
    
    
    UILabel* signLabel = (UILabel*)[cell viewWithTag:3003];
    signLabel.hidden = YES;
    if([item[@"is_teacher"] intValue] == 1)
    {
        int width = [(UILabel*)[cell viewWithTag:1001] sizeThatFits:CGSizeMake(160, 20)].width + 8;
        signLabel.hidden = NO;
        signLabel.frame = CGRectMake(56 + width, 19, 32, 16);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary* item = _mArray[indexPath.row];
    MateInfoViewController* subview = [[MateInfoViewController alloc] init];
    subview.mUserId = [item[@"id"] description];
    [self.navigationController pushViewController:subview animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
